package com.jy.mybatis;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;  
import org.mybatis.generator.api.PluginAdapter;  
import org.mybatis.generator.api.dom.java.*;  
import java.util.List;

/**
 * entity 添加序列化  dao继承泛型基类 entity 继承基类
 * 扩展一个 mybatis generator 插件
 * @author jiangyan
 *
 */
public class GeneratorPlugin extends PluginAdapter {  
	/**
	 * Dao继承的基类包路径
	 */
	private final String rootInterface = "org.formal.common.base";

	private final String daoName = "BaseDao";
	
	/**
	 * 生成dao
	 */
	@Override
	public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		FullyQualifiedJavaType inType = new FullyQualifiedJavaType(daoName + "<" + introspectedTable.getBaseRecordType()	+ ">");
		FullyQualifiedJavaType impPackage = new FullyQualifiedJavaType(rootInterface + "." + daoName);
		interfaze.addSuperInterface(inType);
		interfaze.addImportedType(impPackage);
		interfaze.getMethods().clear();
		return true;
	}
	
	@Override
	public boolean validate(List<String> warnings) {  
		return true;  
	}  

	/**
	 * 生成实体
	 */
	@Override  
	public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,  
			IntrospectedTable introspectedTable) {  
		addSerialVersionUID(topLevelClass, introspectedTable);
		//		topLevelClass.setSuperClass(entityName);
		//		topLevelClass.addImportedType(rootClass + "." + entityName);
		return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
	}  
	
	private void addSerialVersionUID(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		Field field = new Field();
		field.setVisibility(JavaVisibility.PRIVATE);
		field.setType(new FullyQualifiedJavaType("long"));
		field.setStatic(true);
		field.setFinal(true);
		field.setName("serialVersionUID");
		IntrospectedColumn column = new IntrospectedColumn();
		column.setRemarks(topLevelClass.getType().getShortName() + "序列化");
		field.setInitializationString("1L");
		RemarksCommentGenerator commentGenerator = new RemarksCommentGenerator();
		commentGenerator.addFieldComment(field, introspectedTable, column);
		topLevelClass.addField(field);
	}
}

